package cn.itsource.crm.service.impl;

import cn.itsource.crm.domain.Permission;
import cn.itsource.crm.domain.Role;
import cn.itsource.crm.mapper.RoleMapper;
import cn.itsource.crm.mapper.RolePermissonMapper;
import cn.itsource.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RolePermissonMapper rolePermissonMapper;


    /*保存角色的同时保存权限*/
    @Override
    @Transactional
    public void save(Role role) {
        /*保存角色,返回角色id*/
        super.save(role);
        /*保存角色和权限到中间表*/
        saveRolePermission(role);


    }

    /*删除角色时连带删除中间表*/
    @Override
    public void delete(Serializable id) {
        super.delete(id);

        /*删除中间表*/
        rolePermissonMapper.delete(id);
    }

    /*修改时重新设置中间表*/
    @Override
    @Transactional
    public void update(Role role) {
        super.update(role);

        /*先全部删除该角色绑定的权限*/
        rolePermissonMapper.delete(role.getId());

        /*保存角色和权限到中间表*/
        saveRolePermission(role);
    }


    /*保存角色和权限到中间表*/
    private void saveRolePermission(Role role) {
        List<Permission> permissions = role.getPermissions();
        if(permissions.size()==0){
            return;
        }
        List<Map> list = new ArrayList<>();
        for (Permission permission : permissions) {
            HashMap<String, Long> map = new HashMap<>();
            map.put("role_id", role.id);
            map.put("permission_id", permission.id);
            list.add(map);
        }
        rolePermissonMapper.saveList(list);
    }

    @Override
    public List<Role> findAllByTenant(Long tenantId) {
        return roleMapper.findAllByTenant(tenantId);
    }
}
